package cn.moonspace.common.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {

	public static String SUFFIX_JPG = ".jpg";
	public static String SUFFIX_JPG_THUMB = ".242x200.jpg";
	public static String SUFFIX_JPG_THUMB_LARGE = ".570x400.jpg";
	
    /**
     * 生成缩略图
     * @param srcImageFile 源图片文件的File实例      File file = new File("文件名");
     * @param dstImageFileName 待生成的缩略图片完整路径(生成的格式为：image/jpeg);
     * @throws Exception
     */
    public static void makeSmallImage(File srcImageFile,String dstFilePath, String dstFileName, int dstWidthSize, int dstHeightSize) throws Exception {
        FileOutputStream fileOutputStream = null;
        JPEGImageEncoder encoder = null;
        BufferedImage tagImage = null;
        Image srcImage = null;
        try{
            srcImage = ImageIO.read(srcImageFile);
            int srcWidth = srcImage.getWidth(null);//原图片宽度
            int srcHeight = srcImage.getHeight(null);//原图片高度
            int dstWidth = srcWidth;//缩略图宽度
            int dstHeight = srcHeight;//缩略图高度
            float scale = 0;
            //计算缩略图的宽和高
            if(srcHeight < dstHeightSize && srcWidth < dstWidthSize){
            	dstHeight = srcHeight;
            	dstWidth = srcWidth;
            }else if((float)srcHeight/(float)dstHeightSize > (float)srcWidth/(float)dstWidthSize){
            	dstHeight = dstHeightSize;
                scale = (float)srcHeight/(float)dstHeightSize;
                dstWidth = Math.round((float)srcWidth/scale);
            }else{
            	dstWidth = dstWidthSize;
                scale = (float)srcWidth/(float)dstWidthSize;
                dstHeight = Math.round((float)srcHeight/scale);
            }
            //生成缩略图
            tagImage = new BufferedImage(dstWidth,dstHeight,BufferedImage.TYPE_INT_RGB);
            tagImage.getGraphics().drawImage(srcImage,0,0,dstWidth,dstHeight,null);
            fileOutputStream = new FileOutputStream(new File(dstFilePath, dstFileName));
            encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            encoder.encode(tagImage);
            fileOutputStream.close();
            fileOutputStream = null;
        }finally{
            if(fileOutputStream!=null){
                try{
                    fileOutputStream.close();
                }catch(Exception e){
                }
                fileOutputStream = null;
            }
            encoder = null;
            tagImage = null;
            srcImage = null;
            System.gc();
        }
    }
}
